package cn.bugstack.mcp.server.niuke.infrastructure.adapter;

import cn.bugstack.mcp.server.niuke.domain.adapter.INiuKePort;
import cn.bugstack.mcp.server.niuke.domain.model.ArticleFunctionRequest;
import cn.bugstack.mcp.server.niuke.domain.model.ArticleFunctionResponse;
import cn.bugstack.mcp.server.niuke.infrastructure.gateway.NiuKeService;
import cn.bugstack.mcp.server.niuke.infrastructure.gateway.dto.ArticleRequestDTO;
import cn.bugstack.mcp.server.niuke.infrastructure.gateway.dto.ArticleResponseDTO;
import cn.bugstack.mcp.server.niuke.types.properties.NiukeProperties;
import jakarta.annotation.Resource;
import org.springframework.stereotype.Component;
import retrofit2.Call;
import retrofit2.Response;

import java.io.IOException;


@Component
public class NiuKePort implements INiuKePort {

    @Resource
    private NiukeProperties niukeProperties;
    @Resource
    private NiuKeService niuKeService;

    @Override
    public ArticleFunctionResponse createArticle(ArticleFunctionRequest request) throws IOException {
        ArticleRequestDTO requestDTO = new ArticleRequestDTO();
        requestDTO.setTitle(request.getTitle());
        requestDTO.setContent(request.getMarkdownContent());
        Call<ArticleResponseDTO> call = niuKeService.createArticle(requestDTO, niukeProperties.getCookie());
        Response<ArticleResponseDTO> response = call.execute();

        if (response.isSuccessful()){
            ArticleResponseDTO responseDTO = response.body();
            if (null == responseDTO){
                return null;
            }
            ArticleResponseDTO.ArticleData data = responseDTO.getData();
            return ArticleFunctionResponse.builder()
                    .code(responseDTO.getCode())
                    .msg(responseDTO.getMsg())
                    .success(responseDTO.getSuccess())
                    .data(ArticleFunctionResponse.ArticleData.builder()
                            .result(data.getResult())
                            .redirectUrl(data.getRedirectUrl())
                            .build())
                    .build();
        }
        return null;
    }
}
